package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.AddressDao;
import com.itheima.entity.PageResult;
import com.itheima.myExceptions.AssociatedException;
import com.itheima.pojo.Address;
import com.itheima.pojo.Setmeal;
import com.itheima.service.AddressService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;

@Service(interfaceClass = AddressService.class)
@Transactional
public class AddressServiceImp implements AddressService {
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private JedisPool jedisPool;
    @Override
    public void add(Address address) {
      addressDao.add(address);
             //获取图片名称
        String imgName = address.getImg();
        //将图片名称上传到redis(setmealPicDbResources)中
        if (imgName!=null){
            jedisPool.getResource().sadd(RedisConstant.ADDRESS_PIC_DB_RESOURCES, imgName);
        }
    }

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
         Page<Address> page =(Page<Address>)addressDao.findAll(queryString);
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public void delete(Integer id) throws AssociatedException {
        addressDao.delete(id);
    }

    @Override
    public void edit(Address address) {
        System.out.println(address.getId());
        String initImg = addressDao.findImgUrlById(address.getId());
        String lastImg = address.getImg();
        if ((lastImg!=null)&&(!lastImg.equals(initImg))){
            Jedis jedis = jedisPool.getResource();
            jedis.sadd(RedisConstant.ADDRESS_PIC_RESOURCES,lastImg);
            jedis.close();
            QiniuUtils.deleteFileFromQiniu(initImg);
        }
           addressDao.edit(address);

    }


    @Override
    public List<Map> getAddress() {
        List<Map> address = addressDao.getAddress();
        return address;
    }
}
